/**
 * @param {number[]} nums
 * @return {number}
 */
export var arrayNesting = function (nums) {
  let ans = 0
  const visited = new Set()
  for (let i = 0; i < nums.length; i++) {
    let cnt = 0
    while (!visited.has(i)) {
      visited.add(i)
      cnt++
      i = nums[i]
    }
    ans = Math.max(ans, cnt)
  }
  return ans
}

/**
 * 优化（原地标记)
 * @param {number[]} nums
 * @return {number}
 */
export var arrayNesting2 = function (nums) {
  let ans = 0
  for (let i = 0; i < nums.length; i++) {
    let cnt = 0
    while (nums[i] > -1) {
      const num = nums[i]
      nums[i] = -1 // 标记为-1即为已访问
      i = num
      cnt++
    }
    ans = Math.max(ans, cnt)
  }
  return ans
}
